<template>
  <CDialog
    title="编辑同类编码"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    size="default"
    @confirm="submitFlowReq"
    @cancel="dialogVisible = false"
  >
    <CAlert subtitle="多个编码请按多行填写，或以空格、逗号间隔" type="info" class="g-mb16"></CAlert>
    <el-input
      type="textarea"
      v-model="partSuitCode"
      placeholder="请输入"
      :rows="2"
      :autosize="{ minRows: 2 }"
    />
  </CDialog>
</template>

<script lang="ts" setup name="EditCode">
import { withDefaults, defineProps, defineEmits, computed, watch, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CAlert } from '@/components/CAlert';

import { useMessage } from '@/hooks/useMessage';

import type { GetSupplierFormDetailResult } from '@/apis/supplier/model/supplierModel';
import { getListFlowButton, postCompleteUserTask } from '@/apis/todo/flow';

interface FormDialogProps {
  visible: boolean;
  supplierFormInfo: GetSupplierFormDetailResult;
  processInstanceId: string;
}
const props = withDefaults(defineProps<FormDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh', 'success']);
const { createMessage } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    }
  }
);

const loading = ref(false);
const partSuitCode = ref('');

/**
 * 初始化
 */
function init() {
  loading.value = false;
  partSuitCode.value = props.supplierFormInfo.partSuitCode.join(' ');
}

/**
 * 接口请求
 */
async function submitFlowReq() {
  try {
    loading.value = true;
    // 分割回车和空格
    const partSuitCodeArray = partSuitCode.value.split(/\s|\n|,|，/).filter(item => !!item);
    // const processInstanceId = await createSupplierForm({ ...formState, partSuitCode });
    let btnArr = await getListFlowButton(props.processInstanceId);
    const index = btnArr.findIndex(item => item.action == 'SAVE');
    if (index > -1) {
      const item = btnArr[index];
      const params = {
        action: item.action,
        actionComment: '',
        taskId: item.taskId,
        processInstanceId: item.processInstanceId,
        businessKey: item.businessKey,
        completeTask: item.completeTask ?? true,
        businessParams: {
          partSuitCode: partSuitCodeArray,
          feedbackType: props.supplierFormInfo.feedbackType
        }
      };
      await postCompleteUserTask(params);
      createMessage.success('修改成功！');
      emits('refresh');
      dialogVisible.value = false;
    } else {
      createMessage.warning('当前没有权限！');
    }
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}
</script>
